* This do-file creates outcomes related to pulses cropping patterns

*****
* Assemble all the kharif data
*****

tempfile patterns

forvalues y = 1/3 {
	
	if `y'==1 {
	*** K17 PigeonPeas; R18 Peas Lentils GreenGram Fava
		use hhid season crop_code_* crop_pattern_* crop_area_acre_* ///
			using "$k1/Farm/crops.dta", clear
		
		* Combine variables by season
		egen byte cropcode = rowtotal(crop_code_*)
		drop crop_code_*
		rename crop_pattern_* pattern_*
	}
	
	else if `y'>1 {
		*** K18 PigeonPeas; R19 Peas Lentils GreenGram Fava
		*** K19 PigeonPeas; R20 Peas Lentils GreenGram Fava
		clear
		append using "${k`y'}/Farm/crops_k.dta" "${k`y'}/Farm/crops_r.dta", ///
			gen(season) keep(hhid cropcode pattern_* crop_area_acre_*)
	}

	* Combine variables by season
	keep if (cropcode==1 & season==1) | (inlist(cropcode,2,3,5,7) & season==2)
	egen crop_pattern = rowtotal(pattern_*)
	egen crop_area = rowtotal(crop_area_acre_*)
		
	* Plot-level stuff
	gen byte grow_mono = crop_pattern==1 if !missing(crop_pattern)
	gen byte grow_mixd = inrange(crop_pattern,2,4) if !missing(crop_pattern)

	bys hhid cropcode: egen tot_area = total(crop_area)
	foreach pat in mono mixd {
		gen area_`pat' = grow_`pat'*crop_area
		gen frac_`pat' = area_`pat'/tot_area
	}

	* Collapse to household-level
	collapse tot_area (max) grow_* (sum) area_* frac_*, by(hhid season cropcode) fast
	
	* Fillin missing households
	if `y'==1 {
		merge m:1 hhid using "$admin_data/survey_list.dta"
		drop village
		expand 2 if _m==2
		bys hhid: replace season = _n if _m==2
		drop _merge
		recode grow_* (-999 . = 0)
	}
	else if `y'>1 {
		merge m:1 hhid using "$out_data/survey_drops.dta", keepusing(drop_k`y')
		expand 2 if _m==2
		bys hhid: replace season = _n if _m==2
		drop _merge
		recode grow_* (-999 . = 0) if drop_k`y'==0
		drop drop_k`y'
	}

	* Assign cropping type to HH
	gen byte pattern = 0 if !missing(grow_mono)
	replace pattern = 1 if grow_mixd==1
	replace pattern = 2 if grow_mono==1
	label define crop_pattern 0 "None" 1 "Mixed/Border" 2 "Monocrop"
	label values pattern crop_pattern

	gen byte year = `y'
	
	if `y'>1 append using `patterns'
save `patterns', replace
}

order hhid year
save "$out_data/outcome_patterns.dta", replace
